package cn.darkhorse.alarm.service.alarm;

import cn.darkhorse.alarm.pojo.AlarmParameterSettings;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;

/**
 * @author yuanjun
 * @since 2023/4/7 14:50
 */
public class BaseAlarm {
    
    
    /**
     * 其他
     */
   public static Integer ALARM_OTHER = 0;
    /**
     * 限制报警
     */
    public static Integer ALARM_LIMIT_VALUE = 1;
    /**
     * 连续报警
     */
    public static Integer ALARM_CONTINUOUS_VALUE = 2;
    
    /**
     * 开关
     */
    public static Integer ALARM_PARAMETER_TYPE_SWITCH = 0;
    /**
     * 数值
     */
    public static Integer ALARM_PARAMETER_TYPE_NUMERICAL = 1;
    /**
     * 字符
     */
    public static Integer ALARM_PARAMETER_TYPE_CHARACTER = 2;
    /**
     * 枚举类型
     */
    public static Integer ALARM_PARAMETER_TYPE_ENUMERATION = 3;
    /**
     * 二进制
     */
    public static Integer ALARM_PARAMETER_TYPE_BINARY = 4;
    
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    /**
     * 非数值型告警
     * @param settings
     * @param data
     */
    protected void noNumerical(AlarmParameterSettings settings,Map<String,Object> data){
        String value = (String) data.get(settings.getFieldName());
        JSONArray jsonArray = JSONArray.parseArray(settings.getAlarmMessage());
        for (Object o : jsonArray) {
            JSONObject jsonObject=JSONObject.parse(o.toString());
            String alarmValue=jsonObject.getString("value");
            if(value.equals(alarmValue)){
                sendAlarmFlag(settings,data);
                return;
            }
        }
    }
    
    
    
    protected void sendAlarmFlag(AlarmParameterSettings settings,  Map<String, Object> data) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("settingsId",settings.getId());
        jsonObject.put("value",data.get(settings.getFieldName()));
        jsonObject.put("time", data.get("created_at").toString().substring(0,19));
        stringRedisTemplate.opsForList().leftPush("alarm:list",jsonObject.toString());
    }
    
    
    
    
}
